﻿
using Chain.IDAL;
using Chain.Model;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Web;


/// <summary>
/// flag 返回标志值
/// flag=-13 该会员已参加过此活动
/// flag=-12 插入记录表失败或没有奖励数据
/// flag=-11 exception
/// flag=0 Add/update 模型失败
/// flag>0 成功
/// </summary>

public class JoinActivityDecorator
{
}

public abstract class Gifts
{
    public int MemID;

    public int ActivityID;

    public bool IsCovered;

    public Chain.Model.SysUser UserModel;




    public abstract int Create();
}


public abstract class Decorator : Gifts
{
    private Gifts gift;

    public Decorator(Gifts g)
    {
        this.gift = g;
        this.MemID = g.MemID;
        this.ActivityID = g.ActivityID;
        this.UserModel = g.UserModel;
        this.IsCovered = g.IsCovered;
    }

    public override int Create()
    {
        if (gift != null)
        {

            return gift.Create();

        }
        else
        {
            return -1;
        }
    }

}



public class Base : Gifts
{

    public override int Create()
    {
        int flag = 0;
        try
        {


            Chain.Model.Mem_Activity maModel = new Chain.Model.Mem_Activity();
            Chain.BLL.Mem_Activity maBll = new Chain.BLL.Mem_Activity();

            Chain.BLL.Activity_Gifts agBll = new Chain.BLL.Activity_Gifts();
            DataTable dt = agBll.GetAwardsInfo(this.ActivityID);

            //之前活动置为关闭
            flag=(maBll.UpdateClose(this.MemID)?1:0);

            ////插入新活动记录
            //maModel.MemID = this.MemID;
            //maModel.ActivityID = this.ActivityID;
            //maModel.moeny = 0;
            //maModel.score = 0;
            //maModel.CouponTitle = "";
            //maModel.PresentsName = "";
            //maModel.Mem_ShareId = 0;
            //maModel.Mem_ExtendId = 0;
            //maModel.Mem_RebateId = 0;

            //foreach (DataRow dr in dt.Rows)
            //{
            //    switch (dr["type"].ToString().Trim())
            //    {
            //        case "积分":
            //            maModel.score = Convert.ToDecimal(dr["value"].ToString());
            //            break;
            //        case "储值":
            //            maModel.moeny = Convert.ToDecimal(dr["value"].ToString());
            //            break;
            //        case "代金券":
            //            maModel.CouponTitle = dr["value"].ToString();
            //            break;
            //        case "小礼品":
            //            maModel.PresentsName = dr["value"].ToString();
            //            break;
            //        case "分享奖励":
            //            maModel.Mem_ShareId = Convert.ToInt16(dr["ID"].ToString());
            //            break;
            //        case "推广奖励":
            //            maModel.Mem_ExtendId = Convert.ToInt16(dr["ID"].ToString());
            //            break;
            //        case "返利":
            //            maModel.Mem_RebateId = Convert.ToInt16(dr["ID"].ToString());
            //            break;
            //    }
            //}
            //flag = maBll.Add(maModel);
        }
        catch (Exception ex)
        {
            Logs log = new Logs();
            log.LogError(ex);

            flag = -11;
        }

        return flag;

    }


}




public class Awards
{
    /// <summary>
    /// 获取各类奖励类型的ID
    /// </summary>
    /// <param name="type">2积分，3储值，4分享，5推广，6小礼品，7代金券，8返利</param>
    /// <returns></returns>
    public int GetAwardsID(int type, int activityid)
    {
        Chain.Model.Activity_Gifts saModel = new Chain.Model.Activity_Gifts();
        Chain.BLL.Activity_Gifts saBll = new Chain.BLL.Activity_Gifts();

        DataTable dt = saBll.GetItem(activityid);
        int result = 0;
        if (dt != null && dt.Rows.Count > 0)
        {

            result = Convert.ToInt16(dt.Rows[0][type].ToString());
        }

        return result;


    }
}

/// <summary>
/// 日志记录模式错误
/// </summary>
public class Logs
{
    public void LogError(Exception ex)
    {
        string err = "会员系统 Caught in JoinActivityDecorator.cs   \r\nError in:" + HttpContext.Current.Request.Url.ToString() + "\r\nError Message:" + ex.Message.ToString() + "\r\nStack Trace:" + ex.StackTrace.ToString();
        try
        {
            Chain.Model.SysError mdSysError = new Chain.Model.SysError();
            mdSysError.ErrorTime = DateTime.Now;
            mdSysError.ErrorContent = err;
            mdSysError.Ipaddress = PubFunction.ipAdress;
            LoginLogic login = LoginLogic.LoginStatus();
            if (login.IsLoggedOn && (login.LoginUser != null))
            {
                mdSysError.UserID = login.LoginUser.UserID;
                mdSysError.ShopID = login.LoginUser.UserShopID;
            }
            new Chain.BLL.SysError().Add(mdSysError);
        }
        catch (Exception e)
        {
            this.LogError(e);
        }
    }

}




#region 子项


/// <summary>
/// 积分
/// </summary>
public class Score : Decorator
{
    public Score(Gifts g) : base(g)
    {
    }

    public override int Create()
    {
        int flag = 0;
        try
        {
            base.Create();

            Awards award = new Awards();
            int ScoreID = award.GetAwardsID(2, this.ActivityID);



            Chain.BLL.ScoreMoneyAwards smaBll = new Chain.BLL.ScoreMoneyAwards();
            DataTable dt = smaBll.GetItem(ScoreID);

            if (dt != null && dt.Rows.Count > 0)
            {
                //1.插入积分记录表
                Chain.Model.PointLog pointModel = new Chain.Model.PointLog();
                Chain.BLL.PointLog pointBll = new Chain.BLL.PointLog();

                pointModel.PointMemID = this.MemID;
                pointModel.PointNumber = Convert.ToInt32(Convert.ToDouble(dt.Rows[0]["Nums"].ToString()));
                pointModel.PointChangeType = 22;
                pointModel.PointRemark = "活动编号" + this.ActivityID + "奖励进行增加积分,积分变动：[" + dt.Rows[0]["Nums"].ToString() + "],备注：无";
                pointModel.PointShopID = this.UserModel.UserShopID;
                pointModel.PointCreateTime = DateTime.Now;
                pointModel.PointUserID = this.UserModel.UserID;
                pointModel.PointOrderCode = PubFunction.curParameter.strMemPointChangePrefix + DateTime.Now.ToString("yyMMddHHmmssffff");
                pointModel.PointGiveMemID = 0;

                flag = pointBll.Add(pointModel);

                if (flag > 0)
                {

                    //2.修改会员积分总值
                    Chain.BLL.Mem memBll = new Chain.BLL.Mem();
                    flag = memBll.UpdatePoint(this.MemID, Convert.ToInt32(Convert.ToDouble(dt.Rows[0]["Nums"].ToString())));

                    //3.修改店铺积分
                    if (PubFunction.curParameter.bolShopPointManage)
                    {
                        PubFunction.SetShopPoint(this.UserModel.UserID, this.UserModel.UserShopID, Convert.ToInt32(Convert.ToDouble(dt.Rows[0]["Nums"].ToString())), "会员充值扣除店铺积分", 2);
                    }

                    //4.会员升级
                    PubFunction.UpdateMemLevel(new Chain.Model.Mem());

                    //5.插入系统日志
                    PubFunction.SaveSysLog(this.UserModel.UserID, 4, "赠送积分", "活动奖励：推广奖励储值金额:[" + Convert.ToDecimal(dt.Rows[0]["Nums"].ToString()) + "]", this.UserModel.UserShopID, DateTime.Now, PubFunction.ipAdress);
                }
                else
                {
                    flag = -12;
                }
            }
            else
            {
                flag = -12;
            }
        }
        catch (Exception ex)
        {
            Logs log = new Logs();
            log.LogError(ex);
            flag = -11;
        }
        return flag;
    }

}

/// <summary>
/// 储值
/// </summary>
public class Money : Decorator
{
    public Money(Gifts g) : base(g)
    {
    }

    public override int Create()
    {
        int flag = 0;
        try
        {
            base.Create();

            Awards award = new Awards();
            int MoneyID = award.GetAwardsID(3, this.ActivityID);

            Chain.BLL.ScoreMoneyAwards smaBll = new Chain.BLL.ScoreMoneyAwards();
            DataTable dt = smaBll.GetItem(MoneyID);

            if (dt != null && dt.Rows.Count > 0)
            {
                //1.插入储值纪录表
                Chain.Model.MemRecharge moneyModel = new Chain.Model.MemRecharge();
                Chain.BLL.MemRecharge moneyBll = new Chain.BLL.MemRecharge();


                Chain.BLL.Mem bllMem = new Chain.BLL.Mem();
                Chain.Model.Mem modelMem = bllMem.GetModel(this.MemID);

                decimal sumMoney, money, giveMoney = 0M;
                money = Convert.ToDecimal(dt.Rows[0]["Nums"].ToString());
                sumMoney = money + giveMoney;
                int point = 0;

                moneyModel.RechargeMemID = this.MemID;
                moneyModel.RechargeAccount = PubFunction.curParameter.strMemPointChangePrefix + DateTime.Now.ToString("yyMMddHHmmssffff");
                moneyModel.RechargeType = 22;
                moneyModel.RechargeMoney = Convert.ToDecimal(dt.Rows[0]["Nums"].ToString());
                moneyModel.RechargeGive = 0;
                moneyModel.RechargeRemark = "会员账户充值,充值金额：[" + dt.Rows[0]["Nums"].ToString() + "],赠送：[0M],备注：活动编号" + this.ActivityID + "奖励赠送";
                moneyModel.RechargeShopID = this.UserModel.UserShopID;
                moneyModel.RechargeCardBalance = modelMem.MemMoney + sumMoney;
                moneyModel.RechargeIsApprove = true;
                moneyModel.RechargePoint = point;
                moneyModel.RechargeCreateTime = DateTime.Now;

                flag = moneyBll.Add(moneyModel);

                if (flag > 0)
                {
                    //2.修改会员储值总值
                    Chain.BLL.Mem memBll = new Chain.BLL.Mem();
                    flag = memBll.UpdateMoney(this.MemID, Convert.ToDecimal(dt.Rows[0]["Nums"].ToString()));

                    //3.插入储值log表
                    Chain.Model.MoneyChangeLog moneyChangeLogModel = new Chain.Model.MoneyChangeLog();
                    moneyChangeLogModel.MoneyChangeMemID = this.MemID;
                    moneyChangeLogModel.MoneyChangeUserID = this.UserModel.UserID;
                    moneyChangeLogModel.MoneyChangeType = 21;
                    moneyChangeLogModel.MoneyChangeAccount =dt.Rows[0]["Nums"].ToString();
                    moneyChangeLogModel.MoneyChangeMoney = Convert.ToDecimal(dt.Rows[0]["Nums"].ToString());
                    moneyChangeLogModel.MemMoney = Convert.ToDecimal(memBll.GetItemAll(this.MemID).Tables[0].Rows[0]["MemMoney"]);
                    moneyChangeLogModel.MoneyChangeCreateTime = DateTime.Now;
                    moneyChangeLogModel.MoneyChangeGiveMoney = 0;
                    new Chain.BLL.MoneyChangeLog().Add(moneyChangeLogModel);

                    //4.插入系统操作日志
                    PubFunction.SaveSysLog(this.UserModel.UserID, 3, "赠送储值", "活动奖励：推广奖励储值金额:[" + Convert.ToDecimal(dt.Rows[0]["Nums"].ToString()) + "]", this.UserModel.UserShopID, DateTime.Now, PubFunction.ipAdress);
                }
                else
                {
                    flag = -12;
                }
            }
            else
            {

                flag = -12;
            }
        }
        catch (Exception ex)
        {
            Logs log = new Logs();
            log.LogError(ex);
            flag = -11;
        }
        return flag;
    }

}

/// <summary>
/// 推广
/// </summary>
public class Extend : Decorator
{
    public Extend(Gifts g) : base(g)
    {
    }

    public override int Create()
    {
        int flag = 0;
        try
        {

            base.Create();

            Chain.Model.Mem_Extend meModel = new Chain.Model.Mem_Extend();
            Chain.BLL.Mem_Extend meBll = new Chain.BLL.Mem_Extend();

            if (this.IsCovered)
            {
                //1.原纪录置为不可用
                meBll.UpdateClose(this.MemID);

                //2.插入新纪录
                Awards award = new Awards();
                int ExtendID = award.GetAwardsID(5, this.ActivityID);

                Chain.Model.Share_ExtendAwards saModel = new Chain.Model.Share_ExtendAwards();
                Chain.BLL.Share_ExtendAwards saBll = new Chain.BLL.Share_ExtendAwards();


                if (ExtendID > 0)
                {
                    DataTable dt = saBll.GetItem(ExtendID);
                    if (dt != null || dt.Rows.Count > 0)
                    {
                        meModel.MemID = this.MemID;
                        meModel.StartTime = DateTime.Now;
                        meModel.EndTime = DateTime.Now.AddDays(Convert.ToInt16(dt.Rows[0]["Validity"].ToString()));
                        meModel.isonline = 1;
                        meModel.Score = Convert.ToDecimal(dt.Rows[0]["Score"]);
                        meModel.Money = Convert.ToDecimal(dt.Rows[0]["Money"]);
                        meModel.Wxpocket = Convert.ToDecimal(dt.Rows[0]["Wxpocket"]);

                        flag = meBll.Add(meModel);
                    }
                    else
                    {
                        flag = -12;
                    }
                }
                else
                {
                    flag = -12;
                }
            }
            else
            {
                if (!meBll.IsExist(this.MemID))
                {
                    //插入新纪录
                    Awards award = new Awards();
                    int ExtendID = award.GetAwardsID(5, this.ActivityID);

                    Chain.Model.Share_ExtendAwards saModel = new Chain.Model.Share_ExtendAwards();
                    Chain.BLL.Share_ExtendAwards saBll = new Chain.BLL.Share_ExtendAwards();


                    if (ExtendID > 0)
                    {
                        DataTable dt = saBll.GetItem(ExtendID);
                        if (dt != null || dt.Rows.Count > 0)
                        {
                            meModel.MemID = this.MemID;
                            meModel.StartTime = DateTime.Now;
                            meModel.EndTime = DateTime.Now.AddDays(Convert.ToInt16(dt.Rows[0]["Validity"].ToString()));
                            meModel.isonline = 1;
                            meModel.Score = Convert.ToDecimal(dt.Rows[0]["Score"]);
                            meModel.Money = Convert.ToDecimal(dt.Rows[0]["Money"]);
                            meModel.Wxpocket = Convert.ToDecimal(dt.Rows[0]["Wxpocket"]);

                            flag = meBll.Add(meModel);
                        }
                        else
                        {
                            flag = -12;
                        }
                    }
                    else
                    {
                        flag = -12;
                    }

                }
            }

        }
        catch (Exception ex)
        {
            Logs log = new Logs();
            log.LogError(ex);

            flag = -11;
        }
        return flag;
    }

}

/// <summary>
/// 返利
/// </summary>
public class Rebate : Decorator
{
    public Rebate(Gifts g) : base(g)
    {
    }

    public override int Create()
    {
        int flag = 0;
        try
        {

            base.Create();

            Chain.Model.Mem_Rebate mrModel = new Chain.Model.Mem_Rebate();
            Chain.BLL.Mem_Rebate mrBll = new Chain.BLL.Mem_Rebate();


            if (this.IsCovered)
            {

                //1.原数据置为不可用
                mrBll.UpdateClose(this.MemID);

                //2.插入新数据
                Awards award = new Awards();
                int RebateID = award.GetAwardsID(8, this.ActivityID);

                Chain.Model.RebateAwards saModel = new Chain.Model.RebateAwards();
                Chain.BLL.RebateAwards saBll = new Chain.BLL.RebateAwards();


                if (RebateID > 0)
                {
                    DataTable dt = saBll.GetItem(RebateID);
                    if (dt != null || dt.Rows.Count > 0)
                    {
                        mrModel.MemID = this.MemID;
                        mrModel.StartTime = DateTime.Now;
                        mrModel.EndTime = DateTime.Now.AddDays(Convert.ToInt16(dt.Rows[0]["Validity"].ToString()));
                        mrModel.isonline = 1;
                        mrModel.Level1 = Convert.ToDecimal(dt.Rows[0]["Level1"]);
                        mrModel.Level2 = Convert.ToDecimal(dt.Rows[0]["Level2"]);
                        mrModel.Level3 = Convert.ToDecimal(dt.Rows[0]["Level3"]);

                        flag = mrBll.Add(mrModel);

                    }
                    else
                    {
                        flag = -12;
                    }
                }
                else
                {
                    flag = -12;
                }
            }
            else
            {
                if (!mrBll.IsExist(this.MemID))
                {

                    //插入新数据
                    Awards award = new Awards();
                    int RebateID = award.GetAwardsID(8, this.ActivityID);

                    Chain.Model.RebateAwards saModel = new Chain.Model.RebateAwards();
                    Chain.BLL.RebateAwards saBll = new Chain.BLL.RebateAwards();


                    if (RebateID > 0)
                    {
                        DataTable dt = saBll.GetItem(RebateID);
                        if (dt != null || dt.Rows.Count > 0)
                        {
                            mrModel.MemID = this.MemID;
                            mrModel.StartTime = DateTime.Now;
                            mrModel.EndTime = DateTime.Now.AddDays(Convert.ToInt16(dt.Rows[0]["Validity"].ToString()));
                            mrModel.isonline = 1;
                            mrModel.Level1 = Convert.ToDecimal(dt.Rows[0]["Level1"]);
                            mrModel.Level2 = Convert.ToDecimal(dt.Rows[0]["Level2"]);
                            mrModel.Level3 = Convert.ToDecimal(dt.Rows[0]["Level3"]);

                            flag = mrBll.Add(mrModel);

                        }
                        else
                        {
                            flag = -12;
                        }
                    }
                    else
                    {
                        flag = -12;
                    }
                }
            }
        }
        catch (Exception ex)
        {

            Logs log = new Logs();
            log.LogError(ex);

            flag = -11;
        }
        return flag;
    }

}

/// <summary>
/// 分享
/// </summary>
public class Share : Decorator
{
    public Share(Gifts g) : base(g)
    {
    }

    public override int Create()
    {
        int flag = 0;
        try
        {

            base.Create();


            Chain.Model.Mem_Share msModel = new Chain.Model.Mem_Share();
            Chain.BLL.Mem_Share msBll = new Chain.BLL.Mem_Share();

            if (this.IsCovered)
            {

                //1.原数据置为不可用
                msBll.UpdateClose(this.MemID);

                //2.插入新数据
                Awards award = new Awards();
                int ShareID = award.GetAwardsID(4, this.ActivityID);

                Chain.Model.Share_ExtendAwards saModel = new Chain.Model.Share_ExtendAwards();
                Chain.BLL.Share_ExtendAwards saBll = new Chain.BLL.Share_ExtendAwards();


                if (ShareID > 0)
                {
                    DataTable dt = saBll.GetItem(ShareID);
                    if (dt != null || dt.Rows.Count > 0)
                    {
                        msModel.MemID = this.MemID;
                        msModel.StartTime = DateTime.Now;
                        msModel.EndTime = DateTime.Now.AddDays(Convert.ToInt16(dt.Rows[0]["Validity"].ToString()));
                        msModel.isonline = 1;
                        msModel.Score = Convert.ToDecimal(dt.Rows[0]["Score"]);
                        msModel.Money = Convert.ToDecimal(dt.Rows[0]["Money"]);
                        msModel.Wxpocket = Convert.ToDecimal(dt.Rows[0]["Wxpocket"]);
                        msModel.num = Convert.ToInt32(dt.Rows[0]["Limit"]);

                        flag = msBll.Add(msModel);
                    }
                    else
                    {
                        flag = -12;
                    }
                }
                else
                {
                    flag = -12;
                }
            }
            else
            {
                if (!msBll.IsExist(this.MemID))
                {

                    //插入新数据
                    Awards award = new Awards();
                    int ShareID = award.GetAwardsID(4, this.ActivityID);

                    Chain.Model.Share_ExtendAwards saModel = new Chain.Model.Share_ExtendAwards();
                    Chain.BLL.Share_ExtendAwards saBll = new Chain.BLL.Share_ExtendAwards();


                    if (ShareID > 0)
                    {
                        DataTable dt = saBll.GetItem(ShareID);
                        if (dt != null || dt.Rows.Count > 0)
                        {
                            msModel.MemID = this.MemID;
                            msModel.StartTime = DateTime.Now;
                            msModel.EndTime = DateTime.Now.AddDays(Convert.ToInt16(dt.Rows[0]["Validity"].ToString()));
                            msModel.isonline = 1;
                            msModel.Score = Convert.ToDecimal(dt.Rows[0]["Score"]);
                            msModel.Money = Convert.ToDecimal(dt.Rows[0]["Money"]);
                            msModel.Wxpocket = Convert.ToDecimal(dt.Rows[0]["Wxpocket"]);
                            msModel.num = Convert.ToInt32(dt.Rows[0]["Limit"]);

                            flag = msBll.Add(msModel);
                        }
                        else
                        {
                            flag = -12;
                        }
                    }
                    else
                    {
                        flag = -12;
                    }
                }
            }
        }


        catch (Exception ex)
        {
            Logs log = new Logs();
            log.LogError(ex);
            flag = -11;
        }
        return flag;
    }

}

/// <summary>
/// 小礼品
/// </summary>
public class Presents : Decorator
{
    public Presents(Gifts g) : base(g)
    {
    }

    public override int Create()
    {
        return base.Create();
        //现场领取，无操作
    }

}

/// <summary>
/// 代金券
/// </summary>
public class Ticket : Decorator
{
    public Ticket(Gifts g) : base(g)
    {
    }

    public override int Create()
    {
        int flag = 0;
        try
        {
            base.Create();

            Awards award = new Awards();
            int TicketID = award.GetAwardsID(7, this.ActivityID);

            SendCoupon sc = new SendCoupon();
            flag = sc.SendCouponToMem(this.MemID.ToString(), 1, TicketID, this.UserModel);


        }
        catch (Exception ex)
        {
            Logs log = new Logs();
            log.LogError(ex);
            flag = -11;
        }
        return flag;
    }

}

#endregion
